import React from 'react'
import { Form, Input } from 'antd'

type SizeType = 'small' | 'middle' | 'large'

export interface TwoInputFieldsProps {
  // 两个子字段的 key，例如 ['vesselName', 'voyageNumber']
  keys: [string, string]
  // 可选占位文案
  placeholders?: [string?, string?]
  // 透传样式与尺寸
  style?: React.CSSProperties
  size?: SizeType
  disabled?: boolean
  // 来自 Form.Item 的受控值与变更回调（值为对象）
  value?: Record<string, any>
  onChange?: (val: Record<string, any>) => void
}

export const TwoInputFields: React.FC<TwoInputFieldsProps> = ({
  keys,
  placeholders,
  style,
  size = 'middle',
  disabled,
  value,
  onChange,
}) => {
  const form = Form.useFormInstance()

  const [leftKey, rightKey] = keys
  const leftVal = value?.[leftKey] ?? ''
  const rightVal = value?.[rightKey] ?? ''

  const update = (next: Record<string, any>) => {
    onChange?.(next)
    // 同步到顶层字段，便于后续保存直接读取 rest.vesselName / rest.voyageNumber
    // 仅在当前表单实例存在时执行
    if (form) {
      form.setFieldsValue({ [leftKey]: next[leftKey], [rightKey]: next[rightKey] })
    }
  }

  const onLeftChange: React.ChangeEventHandler<HTMLInputElement> = e => {
    const v = e.target.value
    update({ ...(value || {}), [leftKey]: v, [rightKey]: rightVal })
  }

  const onRightChange: React.ChangeEventHandler<HTMLInputElement> = e => {
    const v = e.target.value
    update({ ...(value || {}), [leftKey]: leftVal, [rightKey]: v })
  }

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, ...(style || {}) }}>
      <Input
        value={leftVal}
        onChange={onLeftChange}
        placeholder={placeholders?.[0]}
        size={size}
        disabled={disabled}
        allowClear
      />
      <Input
        value={rightVal}
        onChange={onRightChange}
        placeholder={placeholders?.[1]}
        size={size}
        disabled={disabled}
        allowClear
      />
    </div>
  )
}
